/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.pangalacteos.util;

import br.com.pangalacteos.modelo.DBField;
import br.com.pangalacteos.modelo.DBFieldType;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.swing.JComboBox;

/**
 *
 * @author Leandro Del Sole
 */
public class Mapeator {
    public static Map<Object, DBField> mapeiaComboBD(JComboBox cmbCampo, Class clazz) throws Exception {
        Map<Object, DBField> mapeamento = new HashMap<Object, DBField>();
        Object [] cmbValores = new Object[cmbCampo.getItemCount()];
        for (int i = 0 ; i < cmbCampo.getItemCount() ; i++){
            cmbValores[i] = cmbCampo.getItemAt(i);
            System.out.println("cmbValores[" + i + "] = " + cmbValores[i]);
        }
        
        List<DBField> dbFields = mapeiaDBFields(clazz);
        
        if (dbFields.size() != cmbValores.length){
            System.out.println("dbFields.size " + dbFields.size() 
                    + " cmbValores length " + cmbValores.length);
            throw new Exception("O número de colunas não equivale" +
                    " ao número de valores");
        }
        
        for (int i = 0 ; i < cmbValores.length ; i++){
            mapeamento.put(cmbValores[i], dbFields.get(i));
        }
        return mapeamento;
    }
    
    public static List<DBField> mapeiaDBFields(Class clazz){
        Field [] fields = clazz.getDeclaredFields();
        System.out.println("Fields len" + fields.length);
        List<DBField> dbFields = new ArrayList<DBField>();
        DBField dbField = null;
        for (Field field : fields){
            if (field.isAnnotationPresent(Column.class)){
                //dbColumns[i] = field.getAnnotation(Column.class).name();
                dbField = new DBField(field.getAnnotation(Column.class).name(), 
                        field.getAnnotation(Column.class).columnDefinition());
                dbFields.add(dbField);
            } else if (field.isAnnotationPresent(JoinColumn.class)){
                //dbColumns[i] = field.getAnnotation(JoinColumn.class).name();
                dbField = new DBField(field.getAnnotation(JoinColumn.class).name(), 
                        field.getAnnotation(JoinColumn.class).columnDefinition());
                dbFields.add(dbField);
            } else {
                //TODO: testar anotação JoinColumnS também
                System.out.println("Não tem anotação correspondete. Field: " + field);
                continue;
            }
            System.out.println("dbField " + dbFields.get(dbFields.size() - 1));
        }
        return dbFields;
    }
}
